﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;

namespace Web.Edit
{
    public partial class EditCompany : System.Web.UI.Page
    {
        static long? assignedToID = null;
        static USER user;
        static string prevPage = String.Empty;
        static long OrgID;
        ORGANIZATION org = new ORGANIZATION();
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            assignedToID = null;
            if (Request.UrlReferrer != null)
            {
                prevPage = Request.UrlReferrer.ToString();
                hdntxtPrevPage.Value = prevPage;
            }
             user = (USER)Session["User"];
             if (user != null)
             {
                 r = RoleService.GetRoleByID((long)user.ROLE_ID);
                 if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                 {
                     assignedToID = user.ID;
                     divAssignTo.Visible = false;
                 }
                 string requestEdit = Request.QueryString["id"];
                 if (requestEdit != null)
                 {
                     OrgID = Convert.ToInt64(requestEdit);
                     //Load toan man hinh voi gia tri ORGANIZATION_ID
                     LoadAllUser();
                     LoadOrgIndustry();
                     LoadOrgRating();
                     LoadOrgType();
                     LoadDataOrganizationEdit();
                 }
             }
        }
        private void LoadDataOrganizationEdit()
        {
            ORGANIZATION_DETAIL orgDe = OrganizationService.GetOrganizationDetailByID(OrgID);
            if (orgDe != null)
            {
                //Company Detail
                txtOrganizationName.Text = orgDe.ORGANIZATION_NAME;
                txtCompanyWebsite.Text = orgDe.COMPANY_WEBSITE;
                txtContactNumber.Text = orgDe.CONTACT_NUMBER;
                txtTickerSymbol.Text = orgDe.TICKER_SYMBOL;
                txtFax.Text = orgDe.FAX;
                txtSubsidary.Text = orgDe.MEMBER_OF;
                txtSecondaryPhone.Text = orgDe.PHONE_SECONDARY;
                txtEmployees.Text = orgDe.EMPLOYEE;
                txtPrimaryEmail.Text = orgDe.PRIMARY_EMAIL;
                txtSecondaryEmail.Text = orgDe.SECONDARY_EMAIL;
                txtOwnership.Text = orgDe.OWNERSHIP;
                if (orgDe.INDUSTRY_ID != null)
                    DdlIndustry.FindItemByValue(orgDe.INDUSTRY_ID.ToString()).Selected = true;
                if (orgDe.RATING_ID != null)
                    ddlRating.FindItemByValue(orgDe.RATING_ID.ToString()).Selected = true;
                if (orgDe.TYPE_ID != null)
                    ddlType.FindItemByValue(orgDe.TYPE_ID.ToString()).Selected = true;
                if (orgDe.ASSIGN_TO_ID != null)
                    ddlAssignedTo.FindItemByValue(orgDe.ASSIGN_TO_ID.ToString()).Selected = true;
                txtCompanyRegistrationNumber.Text = orgDe.COMPANY_REGISTRATION_NUMBER;

                //Address Details
                txtOfficeAddress.Text = orgDe.OFFICE_ADDRESS;
                txtHomeAddress.Text = orgDe.HOME_ADDRESS;
                txtOfficePOBox.Text = orgDe.OFFICE_PO_BOX;
                txtHomePOBox.Text = orgDe.HOME_PO_BOX;
                txtOfficeCity.Text = orgDe.OFFICE_CITY;
                txtHomeCity.Text = orgDe.HOME_CITY;
                txtOfficeState.Text = orgDe.OFFICE_STATE;
                txtHomeState.Text = orgDe.HOME_STATE;
                txtOfficePostalCode.Text = orgDe.OFFICE_POSTAL_CODE;
                txtHomePostalCode.Text = orgDe.HOME_POSTAL_CODE;
                txtOfficeCountry.Text = orgDe.OFFICE_COUNTRY;
                txtHomeCountry.Text = orgDe.HOME_COUNTRY;
            }
            else
            {
                divContent.Style["display"] = "none";
                divError.Style["display"] = "block";
            }
        }
        private void LoadOrgType()
        {
            ddlType.DataSource = OrganizationService.GetOrganizationType();
            ddlType.DataBind();
            ddlType.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
        private void LoadOrgRating()
        {
            ddlRating.DataSource = OrganizationService.GetOrganizationRating();
            ddlRating.DataBind();
            ddlRating.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
        private void LoadOrgIndustry()
        {
            DdlIndustry.DataSource = OrganizationService.GetOrganizationIndustry();
            DdlIndustry.DataBind();
            DdlIndustry.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users == null)
            {
                return;
            }
            else
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }
        private int UpdateOrganization()
        {
            org.ID = OrgID;

            DateTime dt = DateTime.Now;
            org.CREATED_BY = 1;//check
            org.DATE_ENTERED = dt;
            org.DATE_MODIFIED = dt;
            // ORGANIZATION DETAILS
            org.ORGANIZATION_NAME = txtOrganizationName.Text;
            org.COMPANY_WEBSITE = txtCompanyWebsite.Text;
            org.CONTACT_NUMBER = txtContactNumber.Text;
            org.TICKER_SYMBOL = txtTickerSymbol.Text;
            org.FAX = txtFax.Text;
            if (hdntxtOrgID.Value != "")
                org.MEMBER_OF_ORG_ID = Convert.ToInt64(hdntxtOrgID.Value);
            else
                org.MEMBER_OF_ORG_ID = null;
            org.PHONE_SECONDARY = txtSecondaryPhone.Text;
            org.EMPLOYEE = txtEmployees.Text;
            org.PRIMARY_EMAIL = txtPrimaryEmail.Text;
            org.SECONDARY_EMAIL = txtSecondaryEmail.Text;
            org.OWNERSHIP = txtOwnership.Text;
            if (DdlIndustry.SelectedValue != "-1")
                org.INDUSTRY_ID = Convert.ToInt64(DdlIndustry.SelectedValue);
            else
                org.INDUSTRY_ID = null;
            if (ddlRating.SelectedValue != "-1")
                org.RATING_ID = Convert.ToInt64(ddlRating.SelectedValue);
            else
                org.RATING_ID = null;
            if (ddlType.SelectedValue != "-1")
                org.TYPE_ID = Convert.ToInt64(ddlType.SelectedValue);
            else
                org.TYPE_ID = null;
            org.ASSIGN_TO = Convert.ToInt64(ddlAssignedTo.SelectedValue);
            org.COMPANY_REGISTRATION_NUMBER = txtCompanyRegistrationNumber.Text;
            // ADDRESS DETAILS
            org.OFFICE_ADDRESS = txtOfficeAddress.Text;
            org.HOME_ADDRESS = txtHomeAddress.Text;
            org.OFFICE_PO_BOX = txtOfficePOBox.Text;
            org.HOME_PO_BOX = txtHomePOBox.Text;
            org.OFFICE_CITY = txtOfficeCity.Text;
            org.HOME_CITY = txtHomeCity.Text;
            org.OFFICE_STATE = txtOfficeState.Text;
            org.HOME_STATE = txtHomeState.Text;
            org.OFFICE_POSTAL_CODE = txtOfficePostalCode.Text;
            org.HOME_POSTAL_CODE = txtHomePostalCode.Text;
            org.OFFICE_COUNTRY = txtOfficeCountry.Text;
            org.HOME_COUNTRY = txtHomeCountry.Text;

            return OrganizationService.UpdateOrganization(org);
        }


        protected void btn_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(prevPage);
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int updateOrganization = UpdateOrganization();
            if (updateOrganization == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Update Company successful !" + "','" + "Companies.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Update Company successful !", "Companies.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not update Company !" + "');");
                //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not update Company !');", true);
        }
        protected void btn_Delete_ServerClick(object sender, EventArgs e)
        {
            org = OrganizationService.GetOrganizationByID(OrgID);
            int OrgDel = OrganizationService.DeleteOrganization(OrgID);
            if (OrgDel == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Delete Company successful !" + "','" + "Companies.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Delete Company successful !", "Companies.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete Company !" + "');");
                //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not delete Company !');", true);
        }
    }
}